package main

import (
	"bytes"
	"crypto/md5"
	"crypto/rand"
	"fmt"
	"github.com/go-redis/redis"
	"math/big"
	"runtime/debug"
	"time"
)

func main()  {

	// 写如1w条10byte数据
	if err := WriteKV(5, 10000, 1); err != nil {
		fmt.Println(err.Error())
		debug.PrintStack()
	}
	//
	//if err := WriteKV(2, 10000, 200); err != nil {
	//	fmt.Println(err.Error())
	//	debug.PrintStack()
	//}
	//
	//if err := WriteKV(3, 10000, 1024); err != nil {
	//	fmt.Println(err.Error())
	//	debug.PrintStack()
	//}
	//
	//if err := WriteKV(4, 10000, 5120); err != nil {
	//	fmt.Println(err.Error())
	//	debug.PrintStack()
	//}

}

func WriteKV(dbNum int, msgCount int, valueSize int) error {
	// 链接redis
	client := redis.NewClient(&redis.Options{
		Addr:     "127.0.0.1:6379",
		Password: "", // no password set
		DB:       dbNum,
	})

	// 写1w条数据
	keyPrefix := time.Now().Unix()
	for i := 0; i < msgCount; i++ {
		key := fmt.Sprintf("%x", md5.Sum([]byte(fmt.Sprint(keyPrefix, "_", i))))
		// 生成指定长度的随机字符串
		value := CreateRandomString(valueSize)
		if err := client.Set(key, value, -1).Err(); err != nil {
			return err
		}
	}
	return nil
}

func CreateRandomString(len int) string  {
	var container string
	var str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
	b := bytes.NewBufferString(str)
	length := b.Len()
	bigInt := big.NewInt(int64(length))
	for i := 0;i < len ;i++  {
		randomInt,_ := rand.Int(rand.Reader,bigInt)
		container += string(str[randomInt.Int64()])
	}
	return container
}
